//
//  PaperViewController.m
//  德方军考通
//
//  Created by 毕武侠 on 2016/11/8.
//  Copyright © 2016年 毕武侠. All rights reserved.
//

#import "PaperViewController.h"
#import "IQKeyboardManager.h"
#import "UINavigationController+FDFullscreenPopGesture.h"

#import "CapabilityAssessmentViewController.h"
#import "PaperAssessmentViewController.h"

#import "PaperViewManager.h"
#import "PaperToolViewManager.h"
#import "PaperReturnViewManager.h"
#import "PaperTimerViewManager.h"
#import "PaperPenViewManager.h"
#import "PaperMoreViewManager.h"
#import "PaperWrongViewManager.h"
#import "PaperFavoriteViewManager.h"
#import "PaperCardViewManager.h"
#import "PaperSendViewManager.h"
#import "CardModel.h"
#import "PaperAnswerModel.h"
#import "PaperAnalyModel.h"
#import "PaperModuleModel.h"
#import "JiGuangUnit.h"


@interface PaperViewController (){
    BOOL _wasKeyboardManagerEnabled;
}

@property (nonatomic, strong) PaperViewManager      *paperViewManager;     // 答题页ViewManager
@property (nonatomic, strong) PaperToolViewManager     *toolViewManager;      // 工具栏ViewManager
@property (nonatomic, strong) PaperReturnViewManager   *returnViewManager;    // 返回ViewManager
@property (nonatomic, strong) PaperTimerViewManager    *timerViewManager;     // 时间ViewManager
@property (nonatomic, strong) PaperPenViewManager      *penViewManager;       // 画板ViewManager
@property (nonatomic, strong) PaperMoreViewManager     *moreViewManager;      // 更多ViewManager
@property (nonatomic, strong) PaperWrongViewManager  *wrongViewManager;     // 纠错ViewManager
@property (nonatomic, strong) PaperFavoriteViewManager *favoriteViewManager;   // 收藏ViewManager
@property (nonatomic, strong) PaperCardViewManager     *cardViewManager;      // 答题卡ViewManager
@property (nonatomic, strong) PaperSendViewManager     *sendViewManager;      // 提交ViewManager

/*  收藏数据源  */
@property(nonatomic,strong)NSMutableArray *newArrDate;

@property(nonatomic,strong)UIButton *shouCnagButon;
@end

@implementation PaperViewController

-(NSMutableArray *)newArrDate{
    if (!_newArrDate) {
        _newArrDate = [NSMutableArray array];

    }
    
    return _newArrDate;
}



- (instancetype)init {
    self = [super init];
    if (self) {
        [self initConfigureView];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.fd_interactivePopDisabled = YES;       // 禁止滑动返回
    [self loadHeadView];
    [self setupConfigureView];
    
}

-(void)addShouCangBtn
{
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(screenWidth - 90, 10, 80, 50)];
    bgView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bgView];
    [bgView addSubview:self.shouCnagButon];
    
    // 1.注册通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationAction:) name:@"InfoNotification" object:nil];
    

    

}
- (void)InfoNotificationAction:(NSNotification *)notification{
    
    NSLog(@"%@",notification.userInfo);
    
//    NSLog(@"---接收到通知---%zd %zd",self.cardViewManager.view.collectionView.step,self.newArrDate.count);
    
    NSInteger tep = [notification.userInfo[@"name"] integerValue];
    
    if (  self.newArrDate.count  == tep) {
        self.shouCnagButon.hidden = YES;
    }else{
        if (self.showPaperAnaly == 1 && _isComeFromShongCang == NO) {
            self.shouCnagButon.hidden = NO;
        }
        
    }

}


-(UIButton *)shouCnagButon{
    if (!_shouCnagButon) {
        UIButton *btn = [UIButton buttonWithType:0];
        btn.frame = CGRectMake(10, 10, 60, 40);
        [btn setTitle:@"收藏" forState:0];
        [btn addTarget:self action:@selector(tongzhi) forControlEvents:(UIControlEventTouchUpInside)];
        _shouCnagButon = btn;
        
    }
    return _shouCnagButon;
}

#pragma mark ---------收藏试题--------------------
- (void)tongzhi{
    
    NSInteger index = self.cardViewManager.view.collectionView.step;

    PaperModuleModel * model = self.newArrDate[index];

    NSLog(@"%zd",index);
    
    NSLog(@"%@",model.ques_id);
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{
                       @"question_id":model.ques_id,
                       @"status":@"1"
                       };
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=Question&a=collectQuestion",HTTPP] parameter:parameter sucess:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NSDictionary *dic = responseObject;
        
        if ([dic[@"status"] intValue] == 200) {
            [MBProgressHUD showTextOnly:kKeyWindow message:dic[@"msg"]];
            
        }else{
            [MBProgressHUD showTextOnly:kKeyWindow message:dic[@"msg"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    _wasKeyboardManagerEnabled = [[IQKeyboardManager sharedManager] isEnabled];
    [[IQKeyboardManager sharedManager] setEnable:NO];
    [self addShouCangBtn];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnable:_wasKeyboardManagerEnabled];
}

- (void)setupConfigureView {
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"f4f4f4"];

    self.dataViewManager = [[PaperDataViewManager alloc] initWithSuperView:self.view];
    self.dataViewManager.title = self.title;
    self.dataViewManager.url = self.url;
    self.dataViewManager.rmodel = self.rmodel;//接受数据模型
    self.dataViewManager.paperIdentifier = self.paperIdentifier;
    self.dataViewManager.receiveIndex = self.receiveIndex;
    self.dataViewManager.showPaperAnaly = self.showPaperAnaly;
    self.dataViewManager.showAnswerAnaly = self.showAnswerAnaly;
    NSLog(@"%d-%d",self.showPaperAnaly,self.showAnswerAnaly);
    
    //显示解析的时候显示收藏按钮
    if (self.showPaperAnaly == 1 && _isComeFromShongCang == NO) {
        self.shouCnagButon.hidden = NO;
    }else{
        self.shouCnagButon.hidden = YES;
    }

    self.dataViewManager.showKnowledge = self.showKnowledge;
    self.dataViewManager.showComment = self.showComment;
    
    // 获取到数据后，加载View
    [self.dataViewManager.receiveSignal subscribeNext:^(NSMutableArray *receive) {
        if (receive.count > 0) {
            
            self.newArrDate = [NSMutableArray array];
            
            for (id Arr in receive) {
                [self.newArrDate addObject:Arr];
            }
            
            
            [self loadViewManager];
        } else {
            [self showLoadViewTo:self.view hidden:NO showPlaceholder:YES message:@"暂无数据"];
        }
    }];
    
    // 加载数据
//    [self.dataViewManager loadDataWithParams:@{@"chapter_id":self.chapter_id}];
    [self.dataViewManager loadDataWithParams:@{self.answerType:self.ID}];

}
// 加载答题页面
- (void)loadViewManager {
    self.paperViewManager = [[PaperViewManager alloc] initWithSuperView:self.view ofDatas:self.dataViewManager.paperDatas];
    
    self.paperViewManager.showToolCard = self.showToolCard;
    self.paperViewManager.showSendView = self.isAllowAnswer;
    if (self.showToolView == YES && self.dataViewManager.paperDatas.count > 0) {
        [self loadToolView];
    }
    
    // 提交数据
    [self loadSendViewManager];
}

// 加载顶部工具栏
- (void)loadToolView {
    self.toolViewManager   = [[PaperToolViewManager alloc] initWithSuperView:self.view ofDatas:self.dataViewManager.paperDatas];      // 工具栏
    
    
    self.returnViewManager = [[PaperReturnViewManager alloc] initWithDatas:self.dataViewManager.paperDatas];    // 退出
    
    self.returnViewManager.isAllowAnswer = self.isAllowAnswer;
    @weakify(self)
    [self.returnViewManager.exitSignal subscribeNext:^(id x) {
        @strongify(self)
        [self deallocCurrentView];
        self.backViewController = nil;
        self.ques_type = nil;
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    
    self.returnViewManager.backSignal = self.toolViewManager.backSignal;
    
    
    
    // 计时功能
    self.toolViewManager.showToolTimer = self.showToolTimer;
    if (self.showToolTimer == YES) {
        [self loadToolTimerView];
    }
    
    // 标题
    self.toolViewManager.showToolTitle = self.showToolTitle;
    if (self.showToolTitle == YES) {
        self.toolViewManager.title = self.title;
    }
    
    // 更多功能
    self.toolViewManager.showToolMore = self.showToolMore;
    if (self.showToolMore == YES) {
        [self loadToolMoreView];
    }
    
    // 答题卡功能
    self.toolViewManager.showToolCard = self.showToolCard;
    if (self.showToolCard == YES) {
        [self loadToolCardView];
    }
    
    // 画板功能
    self.toolViewManager.showToolPen = self.showToolPen;
    if (self.showToolPen == YES) {
        [self loadToolPenView];
    }
    
    self.toolViewManager.showToolSliderView = self.showToolSliderView;
    self.toolViewManager.showToolModuleTitleView = self.showToolModuleTitleView;
    if (self.showToolModuleTitleView == YES) {
        self.paperViewManager.moduleSelectSignal = self.toolViewManager.moveToSignal;
    }
    
    self.toolViewManager.indexSignal = self.paperViewManager.modelSignal;
}

// 加载工具栏时间暂停View
- (void)loadToolTimerView {
    self.timerViewManager  = [[PaperTimerViewManager alloc] initWithSuperView:self.view];
    
    // 工具栏 暂停计时
    self.timerViewManager.restSignal = self.toolViewManager.restSignal;
    // 工具栏 恢复计时
    self.toolViewManager.timeSignal  = self.timerViewManager.hiddenSignal;
}

// 加载工具栏更多View
- (void)loadToolMoreView {
    self.moreViewManager   = [[PaperMoreViewManager alloc] initWithSuperView:self.view ofDatas:self.paperViewManager.datas];      // 更多
    self.moreViewManager.moreSignal = [self.paperViewManager.modelSignal sample:self.toolViewManager.moreSignal];
    
    
    self.wrongViewManager  = [[PaperWrongViewManager alloc] initWithSuperView:self.view];     // 纠错
    // 点击 纠错 功能
    self.wrongViewManager.wrongSignal = [self.paperViewManager.modelSignal sample:self.moreViewManager.wrongSignal];
    
    self.favoriteViewManager = [[PaperFavoriteViewManager alloc] initWithSuperView:self.view];  // 收藏
    self.favoriteViewManager.ques_type = self.ques_type;
    
    // 点击收藏／取消收藏 功能
    self.favoriteViewManager.favoriteSignal = self.moreViewManager.favoriteSignal;
    
    // 收藏成功／取消成功 更新页面
    self.moreViewManager.favoriteReceiveSignal = self.favoriteViewManager.receiveSignal;
    //分享
    [self.moreViewManager.shareSignal subscribeNext:^(id x) {
        NSLog(@"x;%@",x);//
        //PaperAnalyModel PaperAnswerModel
//        JSHAREMessage *message = [JSHAREMessage message];
//        message.mediaType = JSHARELink;

//        if ([x isKindOfClass:[PaperAnalyModel class]]) {
//            PaperAnalyModel * paModel = x;
//            message.url = [[OtherNetworking sharedManager] kShareUrlCourseQuestionHistory:(paModel.ques_id)];
//
//        }else{
//            PaperAnswerModel * paModel = x;
//            message.url = [[OtherNetworking sharedManager] kShareUrlCourseQuestion:(paModel.ques_id)];
//        }
        PaperAnswerModel * paModel = x;
//        NSLog(@"type=%@",paModel.ques_type);
        NSDictionary *dic;
        if (paModel.ques_type.intValue == 1) {//智能刷题 高频错题 考点练习
            dic = @{@"share_type":@"1",@"share_id":paModel.ques_id};
        }else if (paModel.ques_type.intValue == 2){//套卷刷题
            dic = @{@"share_type":@"2",@"share_id":paModel.ques_id};
        }
//        [[JiGuangUnit sharedInstant] shareViewAddSubview:self.view withMessage:message andDic:dic];

    }];
}

// 加载工具栏答题卡View
- (void)loadToolCardView {
    self.cardViewManager   = [[PaperCardViewManager alloc] initWithSuperView:self.view ofDatas:self.dataViewManager.paperDatas];      // 答题卡
    self.cardViewManager.showToolTimer = self.showToolTimer;
    self.cardViewManager.showSendView = self.isAllowAnswer;
    self.cardViewManager.showTitleView = self.showToolCardTitleView;
    
    // 点击工具栏答题卡按钮 显示 答题卡
    self.cardViewManager.cardSignal = self.toolViewManager.cardSignal;
    
    // 点击答题卡上的题号 跳转到 相应的题目上
    self.paperViewManager.cardSelectSignal = self.cardViewManager.cardSelectSignal;
    
//    __weak __typeof(&*self)weakSelf = self;
//    self.cardViewManager.view.collectionView.block = ^(NSInteger index) {
//        if (index >= self.newArrDate.count+1) {
//            weakSelf.shouCnagButon.hidden = YES;
//        }else{
//            weakSelf.shouCnagButon.hidden = NO;
//        }
//    };

//   NSInteger tep =  self.cardViewManager.view.collectionView.step;
    
    
    //添加监听者
//    [self.cardViewManager.view.collectionView addObserver:self forKeyPath:@"step" options: NSKeyValueObservingOptionNew context: nil];

    
}

//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
//
//    NSLog(@"sdsfsfs = %@",change);
//
//
//}

// 加载工具栏画板View
- (void)loadToolPenView {
    self.penViewManager    = [[PaperPenViewManager alloc] initWithSuperView:self.view];       // 画板
    
    // 工具栏 启动 画板功能
    self.penViewManager.penSignal   = [self.paperViewManager.modelSignal sample:self.toolViewManager.penSignal];
}
- (void)sendNotificationCenterParams:(NSNotification *)notification{
    [self.cardViewManager timeroutSendPaper];

    NSMutableArray *answer_data = [NSMutableArray array];
//    __block NSString *report_id = nil;
//    __block NSString *paper_id = nil;
//    __block NSString *chapter_id = nil;//节的ID
    
    [self.toolViewManager.datas enumerateObjectsUsingBlock:^(PaperModuleModel *moduleModel, NSUInteger idx, BOOL * _Nonnull stop) {
//        if (paper_id == nil && moduleModel.paper_id) {
//            paper_id = moduleModel.paper_id;
//        }

        
        
        [moduleModel.module_question enumerateObjectsUsingBlock:^(PaperAnswerModel * _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
            [answer_data addObject:@{@"ques_id" : model.ques_id ? : @"", @"user_answer" : model.answer ? : @""}];
//            if (report_id == nil && model.report_id) {
//                report_id = model.report_id;
//            }
//            if (chapter_id == nil && model.chapter_id) {
//                chapter_id = model.chapter_id;
//            }
//
            
            
        }];
    }];
//    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
//    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
    // 日期转化为字符串
//    NSString *nowString = [fmt stringFromDate:[NSDate date]];
//    NSLog(@"chapter_id:%@-paper_id:%@",chapter_id,paper_id);
    NSMutableDictionary *dic = @{@"answer" : answer_data.mj_JSONString,
//                                 @"report_id"   : report_id ? : @"",
//                                 @"paper_id"    : paper_id ? : @"",
//                                 @"report_sub_time"  : nowString,
                                    self.answerType  : self.ID,
                                 @"report_time_long" : [NSNumber numberWithInteger:[self.toolViewManager getAnswerDuration]]}.mutableCopy;
    
    //NSDictionary * dic = notification.object;
//    NSLog(@"tijiao:%@",dic);
//    return;
    [self submitDataParams:dic];
    
}
- (void)submitDataParams:(NSDictionary *)dict{
    [self.sendViewManager loadDataWithParams:dict];
}
// 加载提交
- (void)loadSendViewManager {
    self.sendViewManager   = [[PaperSendViewManager alloc] initWithSuperView:self.view]; // 提交
    self.sendViewManager.ques_type = self.ques_type;
    
    self.toolViewManager.sendSignal = [self.cardViewManager.sendSignal merge:self.paperViewManager.submitSignal];
    self.sendViewManager.sendSignal = self.toolViewManager.sendSignal;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendNotificationCenterParams:) name:NOTIFICATION_SENDPAPER object:nil];
    
    // 提交试卷后跳转功能
    [self.sendViewManager.receiveSignal subscribeNext:^(id x) {
        
        
        [self deallocCurrentView];
        NSUInteger ques_type = [self.ques_type integerValue];
        if (ques_type < 3 || ques_type == 7 || ques_type == 6 || ques_type == 8) {
            //提交试题完成后
            self.rmodel = @"PaperAnalyModel";
            self.paperIdentifier = @"PaperAnalyID";//解析
            self.showPaperAnaly = YES;
            self.showAnswerAnaly = YES;
            self.isAllowAnswer = NO;
            [self setupConfigureView];
            [self loadViewManager];

            
            
//            NSLog(@"----%@",x);
//            CapabilityAssessmentViewController *viewController = [[CapabilityAssessmentViewController alloc] init];
//            viewController.backViewController = self.backViewController;
//            viewController.model = x;
//            viewController.ques_type = self.ques_type;
//            self.backViewController = nil;
//            self.ques_type = nil;
//            [self.navigationController pushViewController:viewController animated:YES];
        } else if (ques_type == 3) {    // 历年真题
//            PaperAssessmentViewController *viewController = [[PaperAssessmentViewController alloc] init];
//            viewController.backViewController = self.backViewController;
//            viewController.model = x;
//            self.backViewController = nil;
//            self.ques_type = nil;
//            [self.navigationController pushViewController:viewController animated:YES];
        }
    }];
}

#pragma mark - init

- (void)initConfigureView {
    self.showToolView = YES;
    self.showToolTimer = YES;
    self.showToolTitle = YES;
    self.showToolPen = YES;
    self.showToolCard = YES;
    self.showToolMore = YES;
    self.showToolMoreWrong = YES;
    self.showToolMoreFavorite = YES;
    self.showToolMoreShare = YES;
    self.showToolSliderView = YES;
    self.showToolCardTitleView = YES;
    self.isAllowAnswer = YES;
    self.showPaperAnaly = YES;
    self.showAnswerAnaly = YES;
    self.showKnowledge = YES;
    self.showComment = YES;
}
- (void)deallocCurrentView{
    [self.toolViewManager closeTimer];
    [self.cardViewManager closeTimer];
    self.paperViewManager = nil;
    self.toolViewManager = nil;
    self.returnViewManager = nil;
    self.timerViewManager = nil;
    self.penViewManager = nil;
    self.moreViewManager = nil;
    self.wrongViewManager = nil;
    self.favoriteViewManager = nil;
    self.cardViewManager = nil;
    self.sendViewManager = nil;
    
//    self.url = nil;
//    self.params = nil;
//    self.rmodel = nil;
//    self.paperIdentifier = nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}
- (void)dealloc{
    
}

@end
